package com.tramy.cnpush;

import androidx.annotation.NonNull;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.module.annotations.ReactModule;
import com.vivo.push.PushClient;
import com.vivo.push.util.VivoPushException;

@ReactModule(name = VIVOPushModule.NAME)
public class VIVOPushModule extends ReactContextBaseJavaModule {

    public static final String NAME = "VIVOPush";

    public VIVOPushModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    @NonNull
    public String getName() {
        return NAME;
    }

    @ReactMethod
    public void init(Promise promise) {
        try {
            PushClient.getInstance(getReactApplicationContext().getApplicationContext())
                .initialize();
            promise.resolve(0);
        }catch (VivoPushException e) {
            promise.resolve(e.getCode());
        }
    }

    @ReactMethod
    public void isSupportPush(Promise promise) {
        boolean isSupport = PushClient.getInstance(getReactApplicationContext().getApplicationContext())
            .isSupport();
        promise.resolve(isSupport);
    }

    @ReactMethod
    public void register(Callback callback) {
        PushClient.getInstance(getReactApplicationContext().getApplicationContext())
            .turnOnPush((state) -> {
                if (state == 0) {
                    String token = PushClient.getInstance(getReactApplicationContext().getApplicationContext())
                        .getRegId();

                    callback.invoke(token);
                }else {
                    callback.invoke("");
                }
            });
    }

    @ReactMethod
    public void unRegister(Promise promise) {
        PushClient.getInstance(getReactApplicationContext().getApplicationContext())
            .turnOffPush(promise::resolve);
    }

}
